package com.example.demo.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTransferUtil {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * yyyy-MM-dd格式获取当月第一天
     */
    public static String getNow(){
        return dateFormat2.format(new Date());
    }

    public static String getMinMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * yyyy-MM-dd格式获取当月最后一天
     */
    public static String getMaxMonthDate(String date){
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            return dateFormat.format(calendar.getTime());
        }  catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * yyyy-MM格式获取当月第一天
     */
    public static String getFirstDay(String date) {
        String year = date.substring(0,4);
        String month = date.substring(5);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(year));
        c.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        return dateFormat.format(c.getTime());
    }

    /**
     * yyyy-MM格式获取当月最后一天
     */
    public static String getLastDay(String date) {
        String year = date.substring(0,4);
        String month = date.substring(5);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(year));
        c.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(Calendar.DAY_OF_MONTH, lastDay);
        return dateFormat.format(c.getTime());
    }
}
